package com.gitee.l0km.javadocreader.internal;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Unicodes {

	/** 将字符串中的unicode转义字符转为unicode字符 */
	public static String unescapeUnicode(String unicodeStr) {
		if (unicodeStr == null || unicodeStr.length() == 0) {
			return unicodeStr;
		}
		Matcher matcher = Pattern.compile("\\\\u([0-9a-f]{4})").matcher(unicodeStr);
		StringBuilder sb = new StringBuilder();
		int lastAppendPosition = 0;
		while (matcher.find()) {
			sb.append(unicodeStr, lastAppendPosition, matcher.start());
			sb.append((char) Integer.parseInt(matcher.group(1), 16));
			lastAppendPosition = matcher.end();
		}
		sb.append(unicodeStr, lastAppendPosition, unicodeStr.length());
	
		return sb.toString();
	}

	/** Escape all unicode characters in string. */
	public static String escapeUnicode(String s) {
		if (s == null) {
			return s;
		}
		int len = s.length();
		int i = 0;
		while (i < len) {
			char ch = s.charAt(i);
			if (ch > 255) {
				StringBuilder buf = new StringBuilder();
				buf.append(s.substring(0, i));
				while (i < len) {
					ch = s.charAt(i);
					if (ch > 255) {
						buf.append("\\u");
						buf.append(Character.forDigit((ch >> 12) % 16, 16));
						buf.append(Character.forDigit((ch >> 8) % 16, 16));
						buf.append(Character.forDigit((ch >> 4) % 16, 16));
						buf.append(Character.forDigit((ch) % 16, 16));
					} else {
						buf.append(ch);
					}
					i++;
				}
				s = buf.toString();
			} else {
				i++;
			}
		}
		return s;
	}

}
